document.addEventListener('DOMContentLoaded', function () {
    // 轮播图设置
    const slides = document.querySelectorAll('.banner-slide');
    const prevButton = document.querySelector('.banner-prev');
    const nextButton = document.querySelector('.banner-next');
    let currentSlide = 0;

    function showSlide(index) {
        slides.forEach((slide, i) => {
            slide.classList.toggle('active', i === index);
        });
    }

    function nextSlide() {
        currentSlide = (currentSlide + 1) % slides.length;
        showSlide(currentSlide);
    }

    function prevSlide() {
        currentSlide = (currentSlide - 1 + slides.length) % slides.length;
        showSlide(currentSlide);
    }

    prevButton.addEventListener('click', prevSlide);
    nextButton.addEventListener('click', nextSlide);

    // 自动轮播
    let slideInterval = setInterval(nextSlide, 5000);

    // 鼠标悬停时暂停自动轮播
    const banner = document.querySelector('.banner');
    banner.addEventListener('mouseenter', () => {
        clearInterval(slideInterval);
    });

    banner.addEventListener('mouseleave', () => {
        slideInterval = setInterval(nextSlide, 5000);
    });

    // 加载商品数据
    loadProducts();

    // 初始化购物车
    updateCartCount();

    // 检查登录状态
    updateLoginStatus();

    // 登录链接点击事件
    const loginLink = document.getElementById('login-link');
    if (loginLink) {
        loginLink.addEventListener('click', function (e) {
            e.preventDefault();
            if (localStorage.getItem('authToken')) {
                logout();
            } else {
                localStorage.setItem('redirectAfterLogin', window.location.pathname);
                window.location.href = 'login.html';
            }
        });
    }

    // 商品分类筛选
    const categoryButtons = document.querySelectorAll('.category-btn');
    categoryButtons.forEach(button => {
        button.addEventListener('click', function () {
            categoryButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            const category = this.getAttribute('data-category');
            filterProducts(category);
        });
    });
});

// 商品数据加载
async function loadProducts() {
    try {
        const response = await fetch('products.json');
        if (!response.ok) {
            throw new Error('商品数据加载失败');
        }
        const products = await response.json();
        displayProducts(products);
    } catch (error) {
        console.error('加载商品时出错:', error);
        // 显示错误信息或加载备用数据
        displayProducts(getFallbackProducts());
    }
}

// 备用商品数据
function getFallbackProducts() {
    return [
        {
            id: 1,
            name: 'Macbook Air',
            price: 9999,
            description: '这是一个示例商品，用于展示商品列表的基本结构和样式。',
            image: 'images/4.jpg',
            category: '手机'
        },
        {
            id: 2,
            name: 'iphone16 pro',
            price: 14999,
            description: '这是另一个示例商品，具有不同的价格和描述信息。',
            image: 'images/5.jpg',
            category: '平板'
        },
        {
            id: 3,
            name: 'iphone16 promax',
            price: 24999,
            description: '第三个示例商品，用于测试响应式布局和多种商品展示。',
            image: 'images/6.jpg',
            category: '笔记本电脑'
        },
        {
            id: 4,
            name: 'ipone15 plus',
            price: 7999,
            description: '第四个示例商品，用于测试不同的商品类别和筛选功能。',
            image: 'images/7.jpg',
            category: '手表'
        }
    ];
}

// 显示商品列表
function displayProducts(products) {
    const productList = document.getElementById('product-list');
    productList.innerHTML = '';

    if (products.length === 0) {
        productList.innerHTML = '<p class="no-products">暂无商品</p>';
        return;
    }

    products.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.setAttribute('data-category', product.category);
        productCard.innerHTML = `
            <div class="product-image">
                <img src="${product.image}" alt="${product.name}" loading="lazy">
            </div>
            <div class="product-info">
                <h3>${product.name}</h3>
                <div class="product-price">¥${product.price.toFixed(2)}</div>
                <p class="product-description">${product.description}</p>
                <div class="product-actions">
                    <button class="add-to-cart" data-id="${product.id}">
                        <i class="fa fa-shopping-cart"></i> 加入购物车
                    </button>
                    <button class="view-details" data-id="${product.id}">
                        <i class="fa fa-eye"></i> 查看详情
                    </button>
                </div>
            </div>
        `;
        productList.appendChild(productCard);
    });

    // 添加到购物车按钮事件
    document.querySelectorAll('.add-to-cart').forEach(button => {
        button.addEventListener('click', function () {
            const productId = parseInt(this.getAttribute('data-id'));
            addToCart(productId);
        });
    });

    // 查看详情按钮事件
    document.querySelectorAll('.view-details').forEach(button => {
        button.addEventListener('click', function () {
            const productId = parseInt(this.getAttribute('data-id'));
            viewProductDetails(productId);
        });
    });
}

// 商品分类筛选
function filterProducts(category) {
    const productCards = document.querySelectorAll('.product-card');
    productCards.forEach(card => {
        if (category === 'all') {
            card.style.display = 'block';
        } else if (card.getAttribute('data-category') === category) {
            card.style.display = 'block';
        } else {
            card.style.display = 'none';
        }
    });
}

// 添加商品到购物车
function addToCart(productId) {
    // 获取当前购物车
    let cart = JSON.parse(localStorage.getItem('cart')) || [];

    // 检查商品是否已在购物车中
    const existingItemIndex = cart.findIndex(item => item.id === productId);

    if (existingItemIndex !== -1) {
        // 商品已在购物车中，增加数量
        cart[existingItemIndex].quantity += 1;
    } else {
        // 商品不在购物车中，添加新商品
        const product = getProductById(productId);
        if (product) {
            cart.push({
                id: product.id,
                name: product.name,
                price: product.price,
                image: product.image,
                quantity: 1
            });
        }
    }

    // 保存购物车到本地存储
    localStorage.setItem('cart', JSON.stringify(cart));

    // 更新购物车计数
    updateCartCount();

    // 显示添加成功提示
    showToast('商品已添加到购物车');
}

// 获取商品信息
function getProductById(productId) {
    // 这里应该从实际数据源获取商品信息
    // 为简化示例，我们使用前面的备用商品数据
    return getFallbackProducts().find(product => product.id === productId);
}

// 更新购物车计数
function updateCartCount() {
    const cart = JSON.parse(localStorage.getItem('cart')) || [];
    const cartCount = cart.reduce((total, item) => total + item.quantity, 0);
    document.getElementById('cart-count').textContent = cartCount;
}

// 查看商品详情
function viewProductDetails(productId) {
    // 存储要查看的商品ID
    localStorage.setItem('selectedProductId', productId);
    // 跳转到商品详情页
    window.location.href = 'product.html';
}

// 显示提示消息
function showToast(message) {
    // 创建提示元素
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;

    // 添加到页面
    document.body.appendChild(toast);

    // 显示动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);

    // 3秒后隐藏
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(toast);
        }, 300);
    }, 3000);
}

// 登出功能
function logout() {
    // 移除认证令牌
    localStorage.removeItem('authToken');
    localStorage.removeItem('userInfo');

    // 更新登录链接文本
    updateLoginStatus();

    // 显示登出提示
    showToast('已成功登出');

    // 刷新页面或执行其他操作
    setTimeout(() => {
        window.location.reload();
    }, 1500);
}

// 更新登录状态
function updateLoginStatus() {
    const loginLink = document.getElementById('login-link');
    const profileLink = document.querySelector('nav ul li a[href="profile.html"]');

    if (localStorage.getItem('authToken')) {
        loginLink.textContent = '登出';
        loginLink.href = '#';
        loginLink.addEventListener('click', logout);
        if (profileLink) profileLink.style.display = 'block';
    } else {
        loginLink.textContent = '登录';
        loginLink.href = '#';
        loginLink.addEventListener('click', function (e) {
            e.preventDefault();
            localStorage.setItem('redirectAfterLogin', window.location.pathname);
            window.location.href = 'login.html';
        });
        if (profileLink) profileLink.style.display = 'none';
    }
}

// 显示商品列表
function displayProducts(products) {
    const productList = document.getElementById('product-list');
    productList.innerHTML = '';

    if (products.length === 0) {
        productList.innerHTML = '<p class="no-products">暂无商品</p>';
        return;
    }

    products.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'product-card';
        productCard.setAttribute('data-category', product.category);
        productCard.innerHTML = `
            <div class="product-image">
                <img src="${product.image}" alt="${product.name}" loading="lazy">
            </div>
            <div class="product-info">
                <h3>${product.name}</h3>
                <div class="product-price">¥${product.price.toFixed(2)}</div>
                <p class="product-description">${product.description}</p>
                <div class="product-actions">
                    <button class="add-to-cart" data-id="${product.id}">
                        <i class="fa fa-shopping-cart"></i> 加入购物车
                    </button>
                    <button class="view-details" data-id="${product.id}">
                        <i class="fa fa-eye"></i> 查看详情
                    </button>
                </div>
            </div>
        `;
        productList.appendChild(productCard);
    });

    // 添加到购物车按钮事件
    document.querySelectorAll('.add-to-cart').forEach(button => {
        button.addEventListener('click', function () {
            const productId = parseInt(this.getAttribute('data-id'));
            addToCart(productId);
        });
    });

    // 查看详情按钮事件
    document.querySelectorAll('.view-details').forEach(button => {
        button.addEventListener('click', function () {
            const productId = parseInt(this.getAttribute('data-id'));
            viewProductDetails(productId);
        });
    });
}

// 获取所有商品信息
function getAllProducts() {
    // 使用你的原始商品数据
    const products = [
        {
            id: 1,
            name: 'Macbook Air',
            price: 9999,
            description: '轻薄便携的笔记本电脑，适合日常办公和娱乐使用。',
            image: 'https://picsum.photos/seed/macbook/300/200',
            category: '电子产品',
            spec: 'M1芯片/8GB/256GB'
        },
        {
            id: 2,
            name: 'iphone16 pro',
            price: 14999,
            description: '最新款旗舰智能手机，拥有超强拍照能力和处理性能。',
            image: 'https://picsum.photos/seed/iphone/300/200',
            category: '电子产品',
            spec: '128GB/深空黑'
        },
        {
            id: 3,
            name: 'iphone16 promax',
            price: 24999,
            description: '大屏旗舰智能手机，适合追求极致体验的用户。',
            image: 'https://picsum.photos/seed/iphonepromax/300/200',
            category: '电子产品',
            spec: '256GB/金色'
        },
        {
            id: 4,
            name: 'ipone15 plus',
            price: 7999,
            description: '性价比高的智能手机，拥有大屏幕和长续航。',
            image: 'https://picsum.photos/seed/iphone15/300/200',
            category: '电子产品',
            spec: '128GB/蓝色'
        }
    ];
    return products;
}

// 搜索商品
function searchProducts(query) {
    const allProducts = getAllProducts();
    return allProducts.filter(product => {
        return product.name.toLowerCase().includes(query.toLowerCase()) || product.description.toLowerCase().includes(query.toLowerCase());
    });
}

// 页面加载时显示所有商品
document.addEventListener('DOMContentLoaded', function () {
    const allProducts = getAllProducts();
    displayProducts(allProducts);

    // 搜索按钮事件
    const searchButton = document.getElementById('search-button');
    searchButton.addEventListener('click', function () {
        const searchInput = document.getElementById('search-input');
        const query = searchInput.value;
        const searchResults = searchProducts(query);
        displayProducts(searchResults);
    });

    // 搜索输入框按下回车键事件
    const searchInput = document.getElementById('search-input');
    searchInput.addEventListener('keydown', function (event) {
        if (event.key === 'Enter') {
            const query = searchInput.value;
            const searchResults = searchProducts(query);
            displayProducts(searchResults);
        }
    });
});